//
//  VGTextViewCell.swift
//  vgbox
//
//  Created by 宋海胜 on 2019/11/1.
//  Copyright © 2019 Swift Xcode. All rights reserved.
//

import UIKit
import Toast_Swift

class VGTextViewCell: UITableViewCell, UITextViewDelegate {

    public var textDidChangedClosure: ((String) -> Void)?
    
    public var limitNum: Int = 50
    
    public var textView: UITextView = {
        let v: UITextView = UITextView()
        v.font = UIFont.systemFont(ofSize: 15)
        v.textColor = UIColor(hex:0x333333)
        return v
    }()

    
    fileprivate var lastText: String = ""
    
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        initView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    public func configCell(_ model: VGTitleContentModel) {
        textView.text = model.content
        textView.snp.updateConstraints { (make) in
            make.height.equalTo(model.rowHeight)
        }
    }
    
    func aboveBtAction() {
        textView.becomeFirstResponder()
    }
    
    fileprivate func initView() {
        self.selectionStyle = .none
        
        textView.delegate = self
        textView.text = "请输入内容（必填）"
        textView.font = UIFont.systemFont(ofSize: 15)
        addSubview(textView)

        textView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(10)
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview().offset(-10)
            make.height.equalTo(0)
        }
    }
    
    func textViewDidChange(_ textView: UITextView) {
        
        let textVStr = textView.text ?? ""
        if lastText == textView.text {
            
            if textVStr.length > limitNum {
                let str = textVStr.subString(to: limitNum)
                textView.text = str
                self.makeToast("不能超过\(limitNum)字", duration: 1.0)
                textDidChangedClosure?(str)
                print("+++++++++++++\(textVStr)")
            }
        } else {
            lastText = textView.text
            textDidChangedClosure?(textView.text)
        }
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
        if range.length == 1 && text.length == 0
        {
            return true
        } else {
            return true
        }
    }
}
